﻿/***********************************************************************************************
 * 
 * ProjectName: WMSSoft.Lib.WinKStart
 * 
 * Description: Class to read RecentOpenedDocument from Disk
 * 
 * Created:     21.07.2012
 * 
 * Author:      matthias wagler - matthias@WMSSoft.de
 * 
 * Copyright:   Copyright 2012 by WMSSoft.net
 * 
 * License:     GPLv3
 * 
 * History:     21.07.2012 - matthias wagler matthias@WMSSoft.de   -   Created
 * 
 **********************************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WMSSoft.Lib.Basic;
using WMSSoft.Lib.Enums;

namespace WMSSoft.Lib.WinKStart
{
    public class cRecentDocumentReader
    {
        private Dictionary<string, object> _RecentDocumentItems = null;
        private cStartmenuItem _RootRecentDocumentMenuItem = null;
        private cStartmenuItem m_Thread_RecentDocuments_Root = null;
        private Dictionary<string, RecentOpenedDocumentTypeListItem> _RecentOpenedDocumentTypeDictionary = null;

        public event EventHandler UpdateMenuItems;

        public cRecentDocumentReader(Dictionary<string, RecentOpenedDocumentTypeListItem> OpenedDocumentTypeDictionary)
        {
            //init dictionary
            _RecentDocumentItems = new Dictionary<string, object>();
            _RootRecentDocumentMenuItem = new cStartmenuItem("root", "RecentOpenedDocuments", eLinkExecutionTypes.Program, "", eExecutionProcedure.Unknown,
                                                    eItemType.Root, "", null, null, "", "","","");
            
            _RecentOpenedDocumentTypeDictionary = OpenedDocumentTypeDictionary;

            AddCategoriesToParent(_RootRecentDocumentMenuItem);
            LoadRecentDocuments();
            //LoadRecentOpenedDocuments();
        }

        public cStartmenuItem RootMenuItem
        {
            get
            {
                return _RootRecentDocumentMenuItem;
            }
        }

        public cStartmenuItem LoadRecentOpenedDocuments()
        {
            try
            {
                //implements code to read the windows opened files
                string sRecentOpenedDocumentsBasicPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Recent);
                _RootRecentDocumentMenuItem.ContentType = eContentPanelContentType.RecentOpenedDocuments;
                SearchItemsRecursiv(sRecentOpenedDocumentsBasicPath, _RootRecentDocumentMenuItem);

                return _RootRecentDocumentMenuItem;
            }
            catch (Exception Ex)
            {
                //write error to messagebus
                CMessagelogging.AppendMessage("Error while loading recent opened Documents from disk!", Ex, EMessageTypes.Error);
                return null;
            }
        }

        public cStartmenuItem LoadRecentDocuments()
        {
            try
            {
                m_Thread_RecentDocuments_Root = _RootRecentDocumentMenuItem;

                Thread m_StartMenuReader_Thread = new Thread(ThreadMethode_LoadRecentDocuments);
                m_StartMenuReader_Thread.Start();

                return _RootRecentDocumentMenuItem;
            }
            catch (Exception Ex)
            {
                CMessagelogging.AppendMessage("Unable to load Recent Documents!", Ex, EMessageTypes.Error);
                return null;
            }
        }

        private void ThreadMethode_LoadRecentDocuments()
        {
            try
            {
                //implements code to read the windows opened files
                string sRecentOpenedDocumentsBasicPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Recent);
                _RootRecentDocumentMenuItem.ContentType = eContentPanelContentType.RecentOpenedDocuments;
                SearchItemsRecursiv(sRecentOpenedDocumentsBasicPath, m_Thread_RecentDocuments_Root);

                
            }
            catch (Exception Ex)
            {
                //write error to Messagebus
                CMessagelogging.AppendMessage("Error while loading recent opened Documents from disk!", Ex, EMessageTypes.Error);               
            }
            finally
            {
                _RootRecentDocumentMenuItem = m_Thread_RecentDocuments_Root;
                if (UpdateMenuItems != null) UpdateMenuItems(this, EventArgs.Empty);
            }
        }

        /// <summary>
        /// Add Categories readed from Konfig to cStartMenuItem as a Item
        /// </summary>
        /// <param name="Parent"></param>
        private void AddCategoriesToParent(cStartmenuItem Parent)
        {
            try
            {
                if (_RecentOpenedDocumentTypeDictionary != null)
                {
                    if (Parent != null)
                    {
                        Parent.ChildItems.Clear();
                        Dictionary<string, RecentOpenedDocumentTypeListItem>.KeyCollection keycoll = _RecentOpenedDocumentTypeDictionary.Keys; 
                        string CategoryKey = "";
                        cStartmenuItem RecentCategory = null;

                        foreach (string Item in keycoll) {
                           CategoryKey = eContentPanelContentType.RecentOpenedDocuments.ToString();
                           if (_RecentOpenedDocumentTypeDictionary[Item].GroupID.Length > 0)
                           {
                               CategoryKey += "." + _RecentOpenedDocumentTypeDictionary[Item].GroupID;
                           }
                           if (Item == ".FOLDER") CategoryKey +=Item;

                           RecentCategory = null;
                           RecentCategory = new cStartmenuItem(CategoryKey, _RecentOpenedDocumentTypeDictionary[Item].Description, eLinkExecutionTypes.Unknown, "",
                                                               eExecutionProcedure.Unknown, eItemType.None, "", null, _RootRecentDocumentMenuItem, "", "", "", "");
                           if (RecentCategory != null)
                           {
                               Parent.AddChild(RecentCategory);
                           }
                        }
                    }
                }
            }
            catch (Exception Ex)
            {
                //write error to messagebus
                CMessagelogging.AppendMessage("Error while loading recent opened Document  Types!", Ex, EMessageTypes.Error);
            }
        }

        /// <summary>
        /// The Methode read all Files an directories (with all Subdirectories) from his given path
        /// </summary>
        /// <param name="Startfolder">Path to search from</param>
        /// <param name="Parent">Parent to add childs</param>
        private void SearchItemsRecursiv(string Startfolder, cStartmenuItem Parent)
        {
            try
            {
                string[] DirFiles = System.IO.Directory.GetFiles(Startfolder);
                System.Windows.Media.Imaging.BitmapImage myBImg = basic_GraphicHelpers.WPFBitmapFromDrawingImage(WMSSoft.Lib.WinKStart.Properties.Resources.Executable);
                cStartmenuItem myStartmenuItem = null;
                string CategoryName = "";

                foreach (string File in DirFiles)
                {
                    if (Parent != null)
                    {
                        myStartmenuItem = cStartmenuItem.MakeInstance(File, Parent, false );
                        
                        CategoryName = "";
                        //myBImg = basic_GraphicHelpers.GetWPFImageFromIcon(System.Drawing.Icon.ExtractAssociatedIcon(File));
                        //myStartmenuItem = new cStartmenuItem(File, System.IO.Path.GetFileName(File), eLinkExecutionTypes.Program, File, eExecutionProcedure.Unknown, eItemType.Link, "", myBImg, Parent, "");
                        //myStartmenuItem.Image = basic_GraphicHelpers.GetWPFImageFromIcon( System.Drawing.Icon.ExtractAssociatedIcon(File));

                        if (myStartmenuItem != null)
                        {
                            myStartmenuItem.ContentType = eContentPanelContentType.RecentOpenedDocuments;

                            if (_RecentOpenedDocumentTypeDictionary != null)
                            {
                                if (myStartmenuItem.ItemType == eItemType.Link)
                                {
                                    string smyFileExt = System.IO.Path.GetExtension(myStartmenuItem.LinkFilename).ToUpper();
                                    if (_RecentOpenedDocumentTypeDictionary.ContainsKey(smyFileExt) == true)
                                    {
                                        myStartmenuItem.GroupID = _RecentOpenedDocumentTypeDictionary[smyFileExt].GroupID;
                                        CategoryName = myStartmenuItem.ContentType.ToString();
                                        if (myStartmenuItem.GroupID.Length > 0) CategoryName += "." + myStartmenuItem.GroupID;
                                        //CategoryName += "." + myStartmenuItem.ItemType.ToString();

                                        //add this Item as child to parent item
                                        if (Parent.ChildItems.ContainsKey(CategoryName.ToUpper()))
                                            ((cStartmenuItem)Parent.ChildItems[CategoryName.ToUpper()]).AddChild(myStartmenuItem);
                                        else
                                            Parent.AddChild(myStartmenuItem);
                                    }
                                    else
                                    {
                                        //add this Item as child to parent item
                                        Parent.AddChild(myStartmenuItem);
                                    }
                                }
                                else if (myStartmenuItem.ItemType == eItemType.Folder)
                                {
                                    myStartmenuItem.GroupID = _RecentOpenedDocumentTypeDictionary[".FOLDER"].GroupID;
                                    CategoryName = myStartmenuItem.ContentType.ToString();
                                    if (myStartmenuItem.GroupID.Length > 0) CategoryName += "." + myStartmenuItem.GroupID;
                                    CategoryName += "." + myStartmenuItem.ItemType.ToString();

                                    //add this Item as child to parent item
                                    if (Parent.ChildItems.ContainsKey(CategoryName.ToUpper()))
                                        ((cStartmenuItem)Parent.ChildItems[CategoryName.ToUpper()]).AddChild(myStartmenuItem);
                                }
                            }
                            else
                            {
                                //add this Item as child to parent item
                                Parent.AddChild(myStartmenuItem);
                            }
                        }
                    }
                }                

            }
            catch (Exception Ex)
            {
                CMessagelogging.AppendMessage("Error while reading startmenuitems!", Ex, EMessageTypes.Error);
            }
        }
    }
}
